<!--
 * @Author: your name
 * @Date: 2019-10-22 09:06:18
 * @LastEditTime: 2020-10-13 16:07:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /e:\yjp\my_test\vue_plugins\src\views\Websocket.vue
 -->
<template>
<div class="container">
<van-nav-bar title="websocket" left-arrow fixed :border="false"
      @click-left='$router.push("/")'/>
      <van-tag color="#459685">{{last_price}}</van-tag>
      <van-divider/>
      <van-tag color="#459685">{{percent+'%'}}</van-tag>
</div>
</template>
<script>
import pako from "pako";
export default {
    name:"WebSocket",
    data(){
        return{
            percent:'0.00',
            last_price:'0.00'
        }
    },
    mounted(){
        this.initSocket();
    },
    methods:{
        initSocket(){
            const _this = this;
            const ws = new WebSocket("wss://okexcomreal.bafang.com:8443/ws/v3?brokerId=139");
            //"BONE-USDT"
            // const param = {"op":"subscribe","args":["spot/all_ticker_3s"]};
            const param = {"op":"subscribe","args":["spot/ticker:BONE-USDT"]};
            ws.onopen = function () {
                ws.send(JSON.stringify(param));
                console.log('数据发送中。。。');
            }
            ws.onmessage = function (evt) {
                const data = evt.data;
                _this.getData(data);
            }
            ws.onclose = function (){
                console.log('连接断开...');
                ws.open = function () {
                    ws.send(JSON.stringify(param));
                    console.log('重新连接数据发送中。。。');
                }
            }
        },
        getData(blob){
            const reader = new FileReader();
            reader.readAsArrayBuffer(blob,"utf-8");
            reader.onloadend =(e)=>{
                const buffer = e.target.result;
                const ploydata  = new Uint8Array(buffer);
                const msg = pako.inflateRaw(ploydata,{'to':'string'});
                const data = JSON.parse(msg);
                if(data.table){
                    let last_price =  data.data[0].last;
                    let num = (last_price - data.data[0].open_24h)/data.data[0].open_24h*100;
                    let percent = num.toFixed(2);
                    console.log('percent',percent);
                    console.log('last_price',last_price);
                    this.percent = percent;
                    this.last_price = last_price;
                }
            }
        }
    }
}
</script>
<style lang="less" scoped>
</style>